<template>
  <div class="all-trail">
    <div class="search">
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="所属课程">
              <el-select
                v-model="form.lessonName"
                placeholder="请选择课程"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in lessonList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上课班级">
              <el-select
                v-model="form.className"
                placeholder="请选择所在班级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in beginClassList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上课老师">
              <el-select
                v-model="form.teacherName"
                placeholder="请选择上课老师"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in teacherList"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                >
                  {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" style="display: flex">
            <el-form-item label="上课日期">
              <el-date-picker
                v-model="form.cTime"
                type="daterange"
                unlink-panels
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 80%"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-button
              style="width: 20%"
              link
              type="primary"
              @click="setDefaultDate"
            >
              本周
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="manage-students">
      <el-button plain @click="isShowDialog = true">开班试听</el-button>
    </div>
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column
          label="课程名称"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        >
          <template #default="scope">
            <span style="color: #67c23a">{{ scope.row.courseNameC }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="className"
          label="上课班级"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />
        <el-table-column
          property="classRoomName"
          label="上课教室"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />
        <el-table-column
          property="teacherName"
          label="上课老师"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />
        <el-table-column
          property="classDate"
          label="上课日期"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />
        <el-table-column
          label="上课时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        >
          <template #default="scope">
            {{ scope.row.classStartTime }}-{{ scope.row.classEndTime }}
          </template>
        </el-table-column>
        <el-table-column
          property="description"
          label="上课内容"
          show-overflow-tooltip
          :formatter="formatName"
          width="200"
        />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleSignUp(scope.row)">
              跟班试听
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetTrailList"
      />
    </div>
    <el-dialog
      v-model="isShowDialog"
      title="开班试听"
      width="30%"
      align-center
      @close="closeShareDialog"
      @opened="loadContent"
    >
      <el-divider style="margin-top: 0" />
      <div>
        <el-form
          ref="addFormRef"
          style="max-width: 600px"
          :model="addForm"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="班级名称:" prop="classId">
            <el-select
              v-model="addForm.classId"
              placeholder="请选择所在班级"
              style="width: 80%"
              @change="toGetClassCourseList"
              clearable
            >
              <el-option
                v-for="item in beginClassList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="课程名称:" prop="courseId">
            <el-select
              v-model="addForm.courseId"
              placeholder="请选择课程"
              style="width: 80%"
              clearable
            >
              <el-option
                v-for="item in classCourseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="上课日期:" prop="classDates">
            <el-date-picker
              v-model="addForm.classDates"
              type="date"
              placeholder="请选择上课日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="上课时间:" prop="classStartTime">
            <el-time-select
              style="width: 140px"
              v-model="addForm.classStartTime"
              :max-time="addForm.classEndTime"
              class="mr-4"
              placeholder="开始时间"
              start="00:00"
              step="00:05"
              end="23:55"
            />

            <div style="text-align: center; width: 40px; display: inline-block">
              ~
            </div>
            <el-time-select
              style="width: 140px"
              v-model="addForm.classEndTime"
              :min-time="addForm.classStartTime"
              placeholder="结束时间"
              start="00:00"
              step="00:05"
              end="23:55"
            />
          </el-form-item>
          <el-form-item label="上课教室">
            <el-select
              style="width: 80%"
              v-model="addForm.classRoom"
              placeholder="上课教室"
              clearable
            >
              <el-option
                v-for="item in classTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button
              style="padding: 0 10px"
              type="primary"
              link
              @click="openClassType = true"
            >
              新增
            </el-button>
          </el-form-item>
          <el-form-item label="上课老师:" prop="teacherId">
            <el-select
              style="width: 80%"
              v-model="addForm.teacherId"
              placeholder="请选择上课老师"
              clearable
            >
              <el-option
                v-for="item in teacherList"
                :key="item.id"
                :label="item.nickName"
                :value="item.id"
                :disabled="!item.isJob"
              >
                {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="助教老师">
            <el-select
              style="width: 80%"
              v-model="addForm.assistant"
              placeholder="助教老师"
              multiple
              clearable
            >
              <el-option
                v-for="item in teacherList"
                :key="item.id"
                :label="item.nickName"
                :value="item.id"
                :disabled="!item.isJob"
              >
                {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上课内容:">
            <el-input v-model="addForm.description" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmClick"> 确定试听 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="openClassType" title="教室设置" width="500">
      <el-button @click="handleAddClassType" type="primary"> 添加 </el-button>
      <el-form ref="classTypeRef" :model="classTypeForm" label-width="auto">
        <el-table
          class="quotation"
          :data="classTypeForm.copyClassTypeList"
          style="width: 100%; margin-top: 20px"
          max-height="400"
        >
          <el-table-column prop="name" label="教室名称">
            <template #default="scope">
              <el-form-item
                :prop="`copyClassTypeList.${scope.$index}.name`"
                :rules="[
                  {
                    required: true,
                    message: '请输入教室名称',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="handleDeleteClassType(scope.$index)"
                v-if="scope.row.used === '0'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClassTypeList()">取消</el-button>
          <el-button type="primary" @click="updateClassTypeList()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onBeforeMount } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBeginClassList,
  getTrailList,
  getTeacherList,
  getLessonList,
  addAudition,
  addClassTimes,
  getClassCourseList,
} from "@/api/studentManagement/index.js";
import {
  getTLabelListAPI,
  updateTLabelListAPI,
} from "@/api/registrar/classroom";
const { proxy } = getCurrentInstance();
//接收学员ID
const route = useRoute();
const router = useRouter();
const studentsId = route.params.studentsId;
//表单
const ruleFormRef = ref(null);
const form = ref({
  className: "",
  lessonName: "",
  teacherName: "",
  cTime: getDefaultWeekRange(),
});
const setDefaultDate = () => {
  form.value.cTime = getDefaultWeekRange();
  pageNum.value = 1;
  toGetTrailList();
};
// 计算本周的开始和结束日期
function getDefaultWeekRange() {
  const now = new Date();
  const dayOfWeek = now.getDay(); // 获取今天是星期几（0-6，0为周日）
  const monday = new Date(now); // 本周一
  const sunday = new Date(now); // 本周日

  // 计算本周一的日期
  monday.setDate(now.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
  // 计算本周日的日期
  sunday.setDate(now.getDate() + (7 - dayOfWeek));

  return [formatDate(monday), formatDate(sunday)]; // 返回格式化后的日期字符串数组
}
// 格式化日期为 "YYYY-MM-DD"
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
//搜索
const handleQuery = () => {
  pageNum.value = 1;

  toGetTrailList();
};
//重置
const resetQuery = () => {
  form.value = {
    className: "",
    lessonName: "",
    teacherName: "",
    cTime: getDefaultWeekRange(),
  };
  pageNum.value = 1;
  toGetTrailList();
};

//班级老师
const teacherList = ref([]);
const toGetTeacherList = async () => {
  try {
    const res = await getTeacherList({});
    if (res.code == 200) {
      teacherList.value = res.data;
    }
  } catch (error) {
    console.error("获取班级老师下拉列表失败:", error);
  }
};
onMounted(toGetTeacherList);
// toGetTeacherList()

//获取课程列表
const lessonList = ref([]);
const toGetLessonList = async () => {
  try {
    const res = await getLessonList({
      pageNum: 1,
      pageSize: 9999,
      open: 1,
    });
    if (res.code == 200) {
      lessonList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学生的信息失败:", error);
  }
};
onBeforeMount(toGetLessonList);
//获取上课班级列表
const beginClassList = ref([]);
const toGetBeginClassList = async () => {
  try {
    const res = await getBeginClassList({
      pageNum: 1,
      pageSize: 9999,
    });
    if (res.code == 200) {
      beginClassList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学生的信息失败:", error);
  }
};
onBeforeMount(toGetBeginClassList);
//分页器
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
//获取表格数据
const loading = ref(true);
const tableData = ref([]);
const toGetTrailList = async () => {
  loading.value = true;
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    courseId: form.value.lessonName,
    classId: form.value.className,
    teacher: form.value.teacherName,
    classStartTime: form.value.cTime ? form.value.cTime[0] : null,
    classEndTime: form.value.cTime ? form.value.cTime[1] : null,
    listType: 9,
    stuId: studentsId,
  };
  try {
    const res = await getTrailList(params);
    if (res.code == 200) {
      total.value = res.total;
      tableData.value = res.rows;
      loading.value = false;
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  }
};
onMounted(toGetTrailList);
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};

//报名
const handleSignUp = (row) => {
  ElMessageBox.confirm(
    `是否将该同学安排进入【${row.courseNameC}】${row.classDate}${row.classStartTime}~${row.classEndTime}课次试听`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      const {
        teacher,
        classId,
        courseId,
        classStartTime,
        classEndTime,
        classRoom,
        orderNo,
        cofId,
      } = row;
      const params = {
        teacher,
        classId,
        courseId,
        classStartTime,
        classEndTime,
        classRoom,
        orderNo,
        cofId,
      };
      try {
        const res = await addAudition({
          ...params,
          temp: 3,
          classDates: row.classDate,
          ids: [{ id: studentsId, courseId }],
        });
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "试听成功",
          });
          router.replace({
            name: "StudentsDetails",
            params: { studentsId: studentsId },
            query: { active: "4" },
          });
        } else {
          ElMessage({
            type: "error",
            message: "试听失败",
          });
        }
      } catch (error) {
        console.error("报名试听失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消试听",
      });
    });
};

//新建课程部分
const isShowDialog = ref(false);

const addFormRef = ref(null);
const addForm = ref({
  courseId: null,
  classId: null,
  classDates: null,
  classStartTime: null,
  classEndTime: null,
  classRoom: null,
  teacherId: null,
  description: null,
  assistant: [],
});
//表单校验
const rules = reactive({
  courseId: [
    {
      required: true,
      message: "请选择课程名称",
      trigger: "change",
    },
  ],
  classId: [
    {
      required: true,
      message: "请选择班级名称",
      trigger: "change",
    },
  ],
  classDates: [
    {
      type: "date",
      required: true,
      message: "请选择上课日期",
      trigger: "change",
    },
  ],
  classStartTime: [
    { required: true, message: "请选择开始时间", trigger: "change" },
  ],
  // classEndTime: [
  //   { required: true, message: '请选择结束时间', trigger: 'change' },
  //   { validator: validateEndTime, trigger: 'change' },
  // ],
  teacherId: [
    {
      required: true,
      message: "请选择上课老师",
      trigger: "change",
    },
  ],
  // classRoom: [
  //   {
  //     required: true,
  //     message: "请选择上课教室",
  //     trigger: "change",
  //   },
  // ],
});
// function validateEndTime(rule, value, callback) {
//   const { classStartTime } = addForm.value

//   // 确保两个时间都填写
//   if (!classStartTime && !value) {
//     return callback(new Error('请同时选择开始时间和结束时间'))
//   }
//   callback()
// }

//创建教室部分
const roomLoading = ref(false);
const openClassType = ref(false);
const classTypeList = ref([]);
const classTypeForm = ref({
  copyClassTypeList: [],
});
function getClassTypeList() {
  roomLoading.value = true;
  getTLabelListAPI({ lableType: "class_room" }).then((response) => {
    classTypeList.value = response.data;
    classTypeForm.value.copyClassTypeList = [...response.data];
    roomLoading.value = false;
  });
}
onMounted(getClassTypeList);
function handleAddClassType() {
  classTypeForm.value.copyClassTypeList.push({
    id: undefined,
    name: "",
    lableType: "class_room",
    used: "0",
  });
}
function handleDeleteClassType(index) {
  classTypeForm.value.copyClassTypeList.splice(index, 1);
}
function cancelClassTypeList() {
  classTypeForm.value.copyClassTypeList = [...classTypeList.value];
  openClassType.value = false;
}
function updateClassTypeList() {
  proxy.$refs["classTypeRef"].validate((valid) => {
    if (valid) {
      roomLoading.value = true;
      updateTLabelListAPI(classTypeForm.value.copyClassTypeList).then(() => {
        roomLoading.value = false;
        openClassType.value = false;
        getClassTypeList();
      });
    } else {
      proxy.$modal.msgError("教室名称不可为空过，请检查后再提交");
    }
  });
}
const closeShareDialog = () => {
  resetForm();
  isShowDialog.value = false;
};
function cancelClick() {
  closeShareDialog();
}
//班课联动
//获取上课班级列表
const classCourseList = ref([]);
const toGetClassCourseList = async () => {
  addForm.value.courseId = null;
  try {
    const res = await getClassCourseList({
      id: addForm.value.classId,
      open: 1,
    });
    if (res.code == 200) {
      classCourseList.value = res.data.courseList;
    }
  } catch (error) {
    console.error("获取课程信息失败:", error);
  }
};

//提交表单
function confirmClick() {
  proxy.$refs["addFormRef"].validate(async (valid) => {
    if (valid) {
      console.log("addForm", addForm.value);
      ElMessageBox.confirm(`确定试听该节课吗?`)
        .then(async () => {
          try {
            addForm.value.assistant
              ? (addForm.value.assistant = addForm.value.assistant.join(","))
              : (addForm.value.assistant = null);
            const res = await addClassTimes({
              ...addForm.value,
              stuIds: [studentsId],
            });
            if (res.code == 200) {
              closeShareDialog();
              ElMessage({
                type: "success",
                message: "试听成功",
              });
              router.replace({
                name: "StudentsDetails",
                params: { studentsId: studentsId },
                query: { active: "4" },
              });
            }
          } catch (error) {
            console.error("试听失败:", error);
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消报名试听",
          });
        });
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}
//重置表单
const resetForm = () => {
  addForm.value = {
    courseId: null,
    classId: null,
    classDates: null,
    classStartTime: null,
    classEndTime: null,
    classRoom: null,
    teacherId: null,
    description: null,
    assistant: [],
  };
  addFormRef.value.resetFields();
};
function disabledDate(time) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
}
</script>

<style lang="scss" scoped>
.all-trail {
  height: 100%;
  overflow: auto;
  padding-bottom: 30px;
  .search {
    margin-top: 20px;
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
}
</style>
